
<template>
  <div class="bi-container">
    <!-- 分析维度选择 -->
    <div class="dimension-selector">
      <el-select
        v-model="selectedDimensions"
        multiple
        collapse-tags
        collapse-tags-tooltip
        placeholder="选择分析维度"
        class="dimension-select"
      >
        <el-option-group label="业务维度">
          <el-option label="运输类型" value="transport_type" />
          <el-option label="客户类型" value="customer_type" />
          <el-option label="货物类型" value="cargo_type" />
          <el-option label="区域" value="region" />
        </el-option-group>
        <el-option-group label="时间维度">
          <el-option label="日" value="day" />
          <el-option label="周" value="week" />
          <el-option label="月" value="month" />
          <el-option label="季" value="quarter" />
        </el-option-group>
      </el-select>

      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="date-picker"
      />

      <el-button type="primary" @click="generateAnalysis">
        <el-icon><DataAnalysis /></el-icon>生成分析
      </el-button>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="item-icon revenue">
              <el-icon><Money /></el-icon>
            </div>
            <div class="item-info">
              <div class="item-label">总收入</div>
              <div class="item-value">¥{{ formatNumber(overview.revenue) }}</div>
              <div class="item-trend" :class="overview.revenueTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(overview.revenueTrend) }}%
                <el-icon><component :is="overview.revenueTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="item-icon orders">
              <el-icon><Document /></el-icon>
            </div>
            <div class="item-info">
              <div class="item-label">订单数</div>
              <div class="item-value">{{ formatNumber(overview.orders) }}</div>
              <div class="item-trend" :class="overview.ordersTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(overview.ordersTrend) }}%
                <el-icon><component :is="overview.ordersTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="item-icon customers">
              <el-icon><User /></el-icon>
            </div>
            <div class="item-info">
              <div class="item-label">活跃客户</div>
              <div class="item-value">{{ formatNumber(overview.customers) }}</div>
              <div class="item-trend" :class="overview.customersTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(overview.customersTrend) }}%
                <el-icon><component :is="overview.customersTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover">
          <div class="overview-item">
            <div class="item-icon profit">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="item-info">
              <div class="item-label">利润率</div>
              <div class="item-value">{{ overview.profitRate }}%</div>
              <div class="item-trend" :class="overview.profitTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(overview.profitTrend) }}%
                <el-icon><component :is="overview.profitTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分析图表 -->
    <el-row :gutter="20" class="analysis-charts">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>收入趋势分析</span>
              <el-radio-group v-model="revenueChartType" size="small">
                <el-radio-button label="line">折线图</el-radio-button>
                <el-radio-button label="bar">柱状图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <!-- 这里集成实际的图表组件 -->
            <el-empty description="图表加载中...">
              <template #image>
                <el-icon style="font-size: 40px"><TrendCharts /></el-icon>
              </template>
            </el-empty>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>客户分布分析</span>
              <el-radio-group v-model="customerChartType" size="small">
                <el-radio-button label="pie">饼图</el-radio-button>
                <el-radio-button label="map">地图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <!-- 这里集成实际的图表组件 -->
            <el-empty description="图表加载中...">
              <template #image>
                <el-icon style="font-size: 40px"><PieChart /></el-icon>
              </template>
            </el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据明细 -->
    <el-card class="data-details">
      <template #header>
        <div class="card-header">
          <span>数据明细</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索"
              prefix-icon="Search"
              style="width: 200px"
            />
            <el-button-group class="ml-2">
              <el-button @click="exportData">
                <el-icon><Download /></el-icon>导出
              </el-button>
              <el-button type="primary" @click="saveAnalysis">
                <el-icon><DocumentAdd /></el-icon>保存分析
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <el-table :data="filteredData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="region" label="区域" width="100" />
        <el-table-column prop="customerType" label="客户类型" width="120" />
        <el-table-column prop="transportType" label="运输类型" width="120" />
        <el-table-column prop="orders" label="订单数" width="100">
          <template #default="{ row }">
            {{ formatNumber(row.orders) }}
          </template>
        </el-table-column>
        <el-table-column prop="revenue" label="收入" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.revenue) }}
          </template>
        </el-table-column>
        <el-table-column prop="profit" label="利润率" width="100">
          <template #default="{ row }">
            {{ row.profit }}%
          </template>
        </el-table-column>
        <el-table-column prop="trend" label="环比" width="100">
          <template #default="{ row }">
            <span :class="row.trend >= 0 ? 'trend-up' : 'trend-down'">
              {{ row.trend >= 0 ? '+' : '' }}{{ row.trend }}%
            </span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 保存分析对话框 -->
    <el-dialog
      v-model="saveDialogVisible"
      title="保存分析"
      width="500px"
    >
      <el-form
        ref="saveFormRef"
        :model="saveForm"
        :rules="saveRules"
        label-position="top"
      >
        <el-form-item label="分析名称" prop="name">
          <el-input v-model="saveForm.name" placeholder="请输入分析名称" />
        </el-form-item>

        <el-form-item label="分析描述" prop="description">
          <el-input
            v-model="saveForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入分析描述"
          />
        </el-form-item>

        <el-form-item label="共享设置">
          <el-radio-group v-model="saveForm.shareType">
            <el-radio label="private">私有</el-radio>
            <el-radio label="team">团队共享</el-radio>
            <el-radio label="public">公开</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="标签">
          <el-select
            v-model="saveForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
            class="w-full"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSave">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  DataAnalysis,
  Money,
  Document,
  User,
  TrendCharts,
  PieChart,
  Search,
  Download,
  DocumentAdd,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'

// 分析维度
const selectedDimensions = ref(['transport_type', 'region'])
const dateRange = ref([])

// 数据概览
const overview = ref({
  revenue: 1234567.89,
  revenueTrend: 5.2,
  orders: 1234,
  ordersTrend: -2.1,
  customers: 456,
  customersTrend: 3.5,
  profitRate: 25.6,
  profitTrend: 1.8
})

// 图表类型
const revenueChartType = ref('line')
const customerChartType = ref('pie')

// 数据列表
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(100)

// 示例数据
const tableData = ref([
  {
    date: '2025-03-14',
    region: '华东',
    customerType: '企业客户',
    transportType: '整车运输',
    orders: 125,
    revenue: 45678.90,
    profit: 23.5,
    trend: 5.2
  },
  {
    date: '2025-03-14',
    region: '华北',
    customerType: '个人客户',
    transportType: '零担运输',
    orders: 89,
    revenue: 23456.78,
    profit: 21.8,
    trend: -1.5
  }
])

// 过滤后的数据
const filteredData = computed(() => {
  if (!searchKeyword.value) return tableData.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return tableData.value.filter(item => 
    item.region.toLowerCase().includes(keyword) ||
    item.customerType.toLowerCase().includes(keyword) ||
    item.transportType.toLowerCase().includes(keyword)
  )
})

// 保存分析对话框
const saveDialogVisible = ref(false)
const saveFormRef = ref(null)
const saveForm = ref({
  name: '',
  description: '',
  shareType: 'private',
  tags: []
})

// 常用标签
const commonTags = ref([
  '收入分析',
  '客户分析',
  '区域分析',
  '趋势分析'
])

// 表单验证规则
const saveRules = {
  name: [{ required: true, message: '请输入分析名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入分析描述', trigger: 'blur' }]
}

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 生成分析
const generateAnalysis = () => {
  if (selectedDimensions.value.length === 0) {
    ElMessage.warning('请选择至少一个分析维度')
    return
  }
  if (!dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择日期范围')
    return
  }
  ElMessage.success('正在生成分析...')
}

// 导出数据
const exportData = () => {
  ElMessage.success('数据导出中...')
}

// 保存分析
const saveAnalysis = () => {
  saveDialogVisible.value = true
}

// 提交保存
const submitSave = async () => {
  if (!saveFormRef.value) return
  
  try {
    await saveFormRef.value.validate()
    ElMessage.success('分析已保存')
    saveDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 处理分页
const handleSizeChange = (size) => {
  pageSize.value = size
  // 重新加载数据
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  // 重新加载数据
}
</script>

<style scoped>
.bi-container {
  padding: 20px;
}

.dimension-selector {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.dimension-select {
  width: 400px;
}

.date-picker {
  width: 320px;
}

.data-overview {
  margin-bottom: 20px;
}

.overview-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.item-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
}

.item-icon.revenue {
  background-color: #ecf5ff;
  color: #409eff;
}

.item-icon.orders {
  background-color: #f0f9eb;
  color: #67c23a;
}

.item-icon.customers {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.item-icon.profit {
  background-color: #fef0f0;
  color: #f56c6c;
}

.item-info {
  flex: 1;
}

.item-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.item-value {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-text-color-primary);
  margin: 4px 0;
}

.item-trend {
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.item-trend.up {
  color: #67c23a;
}

.item-trend.down {
  color: #f56c6c;
}

.analysis-charts {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.ml-2 {
  margin-left: 8px;
}

.w-full {
  width: 100%;
}

:deep(.el-card__header) {
  padding: 12px 20px;
}
</style>